package com.computer.network.util;

import org.springframework.stereotype.Component;

import java.io.Serializable;

/**
 * 统一返回类
 * 易错（需要提供get，set方法。不然json序列化为空）
 *
 * @Author cgs
 * @Date 2022/8/18 10:16
 */
@Component
public class Result<T> implements Serializable {
    private Integer code = null;
    private String message = null;
    private T data = null;

    /**
     * 返回成功，不带返回值
     */
    public Result() {
    }

    /**
     * 返回成功.不带数据
     *
     * @param code
     * @return
     */
    public Result<T> ok(Integer code) {
        Result<T> result = new Result<>();
        result.code = code;
        result.message = "执行成功";
        return result;
    }

    /**
     * 返回成功，带数据
     *
     * @param code
     * @param data
     * @return
     */
    public Result<T> ok(Integer code, T data) {
        Result<T> result = new Result<>();
        result.code = code;
        result.message = "执行成功";
        result.data = data;
        return result;
    }

    /**
     * 返回失败，不带参数
     *
     * @return
     */
    public Result<T> error() {
        Result<T> result = new Result<T>();
        return result;
    }

    /**
     * 返回成功，带code参数
     *
     * @param code
     * @return
     */
    public Result<T> error(Integer code, String message) {
        Result<T> result = new Result<T>();
        result.code = code;
        result.message = message;
        return result;
    }

    /**
     * 返回成功，带code，data参数
     *
     * @param code
     * @param data
     * @return
     */
    public Result<T> error(Integer code, String message, T data) {
        Result<T> result = new Result<T>();
        result.code = code;
        result.message = message;
        result.data = data;
        return result;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "Result{" +
                "code=" + code +
                ", message='" + message + '\'' +
                ", data=" + data +
                '}';
    }
}
